<?php

namespace App\Http\Controllers\CallingCards\Wechat;

use App\Http\Controllers\BaseController;
use App\Library\Freeker\FreekerApi;
use App\Models\Common\ConfigModel;
use App\Models\FeishuCallingCard\FeishuCallingCard;
use App\Models\FeishuCallingCard\FeishuCallingCardsArticle;
use App\Remote\Rms\RmsUserRemote;
use App\Service\CallingCards\RegionalCodeService;
use App\Service\CallingCards\ShopService;
use App\Service\CallingCards\WechatService;
use App\Service\OpenShop\User\RmsUserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Kuafu\File\FileUtil;

class FranchiseeController extends BaseController
{

    /*
     * 微信提交加盟商线索
     */
    public function save(Request $request)
    {
        $request->validate([
            'name'     => 'required',
            'mobile'   => 'required|string|max:20',
            'province' => 'required',
            'city'     => 'required',
        ]);
        $nameRegular   = '/^[A-Za-z0-9_\x{4e00}-\x{9fa5}]+$/u';
        $mobileRegular = '/^1\d{10}$/';
        if (!preg_match($nameRegular, $request->name) || !preg_match($mobileRegular, $request->mobile)) {
            return $this->fail(0, '姓名或手机号输入有误');
        }
        $name          = (string)$request->post('name');
        $mobile        = (string)$request->post('mobile');
        $openid        = auth('callingCardsWeChat')->user()->openid;
        $province      = (string)$request->post('province');
        $city          = (string)$request->post('city');
        $district      = (string)$request->post('district');
        $detailAddress = (string)$request->post('detailAddress');
        $fullInvitorId = (string)$request->post('invitorId');
        $clientIp      = $request->ip();
        if (strlen($fullInvitorId)) {
            auth('callingCardsWeChat')->user()->invitorId = $fullInvitorId;
            auth('callingCardsWeChat')->user()->save();
        } else {
            // 如果是自然流量，则获取本人的invitorId
            $fullInvitorId = auth('callingCardsWeChat')->user()->invitorId;
        }
        $salesName      = '';
        $departmentName = '';
        $invitorMobile  = '';
        if (is_numeric($fullInvitorId)) {
            // 同步到销氪
            $info           = FeishuCallingCard::find($fullInvitorId);
            $salesName      = $info->realname ?? '';
            $departmentName = $info->departmentName ?? '';
        } else {
            if ('u' === mb_substr($fullInvitorId, 0, 1)) {
                $uid           = mb_substr(explode('s', $fullInvitorId)[0], 1);
                $body          = RmsUserService::getRmsUserInfoByUserIds([$uid]);
                $salesName     = $body['data'][0]['username'];
                $invitorMobile = $body['data'][0]['mobile'];
            }
        }
        $arr             = RegionalCodeService::getCodeByAddress($province, $city);
        $arr['province'] = $province;
        $arr['city']     = $city;
        $arr['district'] = '';

        $remark = '';
        if (auth('callingCardsWeChat')->user()->shopId > 0) {
            $shopInfo = ShopService::shopInfoById(auth('callingCardsWeChat')->user()->shopId);
            if (isset($shopInfo['data']['name'])) {
                $remark = "店铺：{$shopInfo['data']['name']}，ID：" . auth('callingCardsWeChat')->user()->shopId;
            }
        }
        $res = (new FreekerApi)->createClue($name, $mobile, explode('s', $fullInvitorId)[0], $salesName, $arr,
            $departmentName, '夸父名片', $remark, '夸父名片', $invitorMobile);
        if ($res['code']) {
            $clueId = $res['data']['key'];
        } else {
            $clueId = '';
        }
        WechatService::addFranchiseeClues($name, $mobile, $openid, $province, $city, $district, $detailAddress,
            $fullInvitorId, $clueId, $clientIp, $remark);

        // 同步 RMS 更新用户操作日志行为
        RmsUserRemote::addUserActionLog(auth('callingCardsWeChat')->user()->unionid ?? '',
            auth('callingCardsWeChat')->user()->shopId ?? '');


        return $this->success();
    }

    public function articles(Request $request)
    {
        return $this->success([
            'list' => FeishuCallingCardsArticle::query()
                ->where('type', (int)$request->type)
                ->where('status', FeishuCallingCardsArticle::STATUS_ON)
                ->orderBy('weight', 'desc')
                ->orderBy('id', 'desc')
                ->get()
                ->map(function (FeishuCallingCardsArticle $article) {
                    $arr = $article->toArray();
                    if (strlen($arr['originalImage'])) {
                        $arr['originalImage'] = FileUtil::domain() . '/' . ltrim($arr['originalImage'],
                                '/');
                    }
                    if (strlen($arr['thumbImage'])) {
                        $arr['thumbImage'] = FileUtil::domain() . '/' . ltrim($arr['thumbImage'],
                                '/');
                    }
                    return $arr;
                })->toArray(),
        ]);
    }

    /**
     * 两级地址，省-市
     * @return JsonResponse
     */
    public function areas(): JsonResponse
    {
        $list = ConfigModel::getValueNewJson('callingCards', 'xiaokeAreas', 600);
        return $this->success($list);
    }
}
